package com.xc.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

//Service，Mapper，RestController祖宗类注解
@Component
public class MyALiYunOSSUtilsPlus {

    /**
     * 创建对象调用
     * 都加注解了
     * 所以把 成员变量 与 方法 的static去掉
     */
    @Value("${aliyun.oss.endpoint}")
    private String endPoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private MyALiYunOSSUtilsPlus(){

    }

    public String uploadFile(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

       /* String accessKeyId = "";// 按自己的实际情况填写
        String accessKeySecret = "";
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);*/

        // 填写Bucket名称，例如examplebucket。
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        // 准备上传的文件 - io流

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider);

        try {
            //  putObject 方法的第一个参数表示 bucketName,第2个参数表示上传后的文件名,第3个参数表示要上传的文件对象
            // 1: 获取真实文件名
            String filename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            filename= UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
            ossClient.putObject(bucketName, filename, inputStream);
            // 自己按规律url拼接  https://bucketName.endPoint/filename
            StringBuilder sb = new StringBuilder("https://");
            sb.append(bucketName).append(".").append(endPoint.substring(endPoint.lastIndexOf("/")+1)).append("/").append(filename);
            return sb.toString();

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;

    }


}